﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;
//using System.Web.Mvc;

namespace Infrastructure.WebApi.Middleware
{
    /// <summary>
    /// 模型绑定错误重写
    /// </summary>
    public class ModelBindFilter : IActionFilter
    {
        /*Startup中配置
          services.Configure<ApiBehaviorOptions>(options =>
          {
              options.SuppressModelStateInvalidFilter = true;
          });
         */
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var listErrorMessage = new List<string>();
                #region 组合errorMessage
                foreach (var item in context.ModelState.Values)
                {
                    var errorSb = new StringBuilder();
                    foreach (var error in item.Errors)
                    {
                        errorSb.Append(error.ErrorMessage).Append(" ");
                    }
                    listErrorMessage.Add(errorSb.ToString().TrimEnd());
                }
                #endregion
                context.Result = new JsonResult(new ResponseBase { Msg = string.Join("\r\n", listErrorMessage), Code = ApiCode.RequestError });
                return;
            }
        }
        public void OnActionExecuted(ActionExecutedContext context) { }
    }

    public class TrimFilter : Attribute, IActionFilter
    {
        /*Startup中配置
          services.Configure<ApiBehaviorOptions>(options =>
          {
              options.SuppressModelStateInvalidFilter = true;
          });
         */
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var listErrorMessage = new List<string>();
                #region 组合errorMessage
                foreach (var item in context.ModelState.Values)
                {
                    var errorSb = new StringBuilder();
                    foreach (var error in item.Errors)
                    {
                        errorSb.Append(error.ErrorMessage).Append(" ");
                    }
                    listErrorMessage.Add(errorSb.ToString().TrimEnd());
                }
                #endregion
                context.Result = new JsonResult(new ResponseBase { Msg = string.Join("\r\n", listErrorMessage), Code = ApiCode.RequestError });
                return;
            }
        }
        public void OnActionExecuted(ActionExecutedContext context) { }
    }
}
